<?php

namespace app\wxapp\controller;

use app\common\model\Order as OrderModel;
use app\common\model\StudyPlan as StudyPlanModel;
use app\common\model\Vip as VipModel;
use app\common\service\UserService;
use app\wxapp\model\WechatUser as WechatUserModel;
use app\common\wxpay\lib\WxPayResults;
use think\facade\Db;


class Open
{

    /**
     * 微信支付通知
     */
    public function notify()
    {
        $xml = file_get_contents("php://input");
        Db::table("just_record")->insert([
            'content' => $xml,
            'create_time' => date('Y-m-d H:i:s')
        ]);


        $wxPayResult = new WxPayResults();
        $res = $wxPayResult->FromXml($xml);

        if ($res['result_code'] == 'SUCCESS' && $res['return_code'] == 'SUCCESS') {
            $processData = [];
            $processData['totalFee'] = $res['total_fee'];
            $processData['tradeNo'] = $res['out_trade_no'];
            $processData['openid'] = $res['openid'];
            $processData['transactionId'] = $res['transaction_id']; //用于查询

            $order = Db::table('order')->where(['order_sn' => $processData['tradeNo']])->find();
            if ($order['status'] == 1 || empty($order)) {
                $this->sendMsg();
            }
            $order['transaction_id'] = $processData['transactionId'];
            $order['openid'] = $processData['openid'];
            $order['status'] = 1;
            $order['pay_time'] = date('Y-m-d H:i:s', time());

            //更新订单状态
            $order = OrderModel::update($order, ['id' => $order['id']]);

            Db::table("just_record")->insert([
                'content' => json_encode($order),
                'create_time' => date('Y-m-d H:i:s')
            ]);

            try {
                //针对每种情况做特殊处理
                if ($order['type'] == OrderModel::VIDEO) {
                    $this->processVideo($order);
                } else if ($order['type'] == OrderModel::TOPIC) {
                    $this->processTopic($order);
                } else if ($order['type'] == OrderModel::VIP) {
                    $this->processVip($order);
                }
            } catch (\Exception $e) {
                Db::table("just_record")->insert([
                    'content' => $e->getMessage(),
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }


        }
        $this->sendMsg();

        exit;

    }

    private function sendMsg()
    {
        $xml = <<<code
<xml> 
    <return_code><![CDATA[SUCCESS]]></return_code>
    <return_msg><![CDATA]></return_msg> 
</xml>
code;
        echo $xml;
        exit;
    }

    private function processVideo($order)
    {
        $user = Db::table('wechat_user')->where(['openid' => $order['openid']])->find();

        $studyPlan = [];
        $studyPlan['src_id'] = $order['src_id'];
        $studyPlan['type'] = StudyPlanModel::VIDEO;
        $studyPlan['uid'] = $user['id'];
        $studyPlan['order_id'] = $order['id'];

        StudyPlanModel::create($studyPlan);
    }

    private function processTopic($order)
    {
        $user = Db::table('wechat_user')->where(['openid' => $order['openid']])->find();

        $studyPlan = [];
        $studyPlan['src_id'] = $order['src_id'];
        $studyPlan['type'] = StudyPlanModel::TOPIC;
        $studyPlan['uid'] = $user['id'];
        $studyPlan['order_id'] = $order['id'];

        StudyPlanModel::create($studyPlan);
    }

    private function processVip($order)
    {
        // 查询VIP配置
        $vip = VipModel::getById($order['src_id']);
        // 查询原有VIP
        $vipInfo = UserService::getVipInfo($order['uid']);
        if ($vipInfo) {
            // 已有VIP则更新
            $oldVip = VipModel::getById($vipInfo['id']);
            if ($vip->time_unit > $oldVip->time_unit || ($vip->time_unit == $oldVip->time_unit && $vip->time_expire > $oldVip->time_expire)) {
                // 本次开通的VIP时长比之前开通的VIP时长更长则替换VIP ID
                UserService::setExtValue($order['uid'], UserService::TYPE_EXT_VIP_ID, $vip->id);
            }
            $expire = $vip->getTime(strtotime($vipInfo['expire']));
        } else {
            // 记录VIP ID
            UserService::setExtValue($order['uid'], UserService::TYPE_EXT_VIP_ID, $vip->id);
            // 更新过期时间
            $expire = $vip->getTime(time());
            // 记录开启VIP时间
            UserService::setExtValue($order['uid'], UserService::TYPE_EXT_VIP_START, date('Y-m-d'));
        }
        // 追加VIP有效时间
        UserService::setExtValue($order['uid'], UserService::TYPE_EXT_VIP_EXPIRE, $expire);
    }
}